package com.lilicould.controller;

import com.google.gson.Gson;
import com.lilicould.entity.StudentsDetails;
import com.lilicould.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/student/*")
public class StudentController extends BaseServlet{

    // 获取一个学生信息
    public void get(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String userNo = req.getParameter("userNo");
        String result = new StudentService().getStudent(userNo);
        if (result != null) {
            // 若返回数据非空，说明成功获取到数据，则返回数据给前端
            resp.setStatus(HttpServletResponse.SC_OK);
            out.write(result);
        } else {
            // 若返回结果为空，说明获取数据失败，则返回错误信息给前端
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    // 获取所有学生信息
    public void listAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String result = new StudentService().getAllStudents();
        out.write(result);
    }

    // 添加一个学生信息
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setContentType("application/json;charset=utf-8");
        // 获取请求中的json数据
        String json = req.getReader().readLine();
        // 将json数据转换成StudentsDetails对象
        StudentsDetails studentsDetails = new Gson().fromJson(json, StudentsDetails.class);

        // 使用服务层添加学生信息
        String result = new StudentService().addStudent(studentsDetails);

        PrintWriter out = resp.getWriter();
        String resultJson = new Gson().toJson(result);
        // 若不为空，则返回错误信息
        if (result != null){
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write(resultJson);
        } else {
            // 添加成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }

    }

    // 删除一个学生信息
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setContentType("application/json;charset=utf-8");
        String id = req.getParameter("id");
        String result = new StudentService().deleteStudent(id);
        String jsonResult = new Gson().toJson(result);
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            PrintWriter out = resp.getWriter();
            out.write(jsonResult);
        } else {
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }
}
